package wsz.file.util;

/**
 * @author wsz
 * @date 2022/4/6 15:24
 **/
public class SpeedLimit {

    private static Long KB = 1024L;

    private static Long CHUNK_LENGTH = 1024L;

    private int bytes = 0;

    private long lastTick = System.nanoTime();

    private int max = 1024;

    private long time = (1000000000L * CHUNK_LENGTH) / (max * KB);


    public SpeedLimit(int max) {
        this.max = max < 0 ? 0 : max;

        if (max == 0) {
            this.time = 0;
        } else {
            this.time = (1000000000L * CHUNK_LENGTH) / (max * KB);
        }
    }

    public void doLimit(int len) {
        this.bytes += len;

        while(this.bytes > CHUNK_LENGTH) {
            long nowTick = System.nanoTime();

            long missedTime = this.time - (nowTick - this.lastTick);
            if (missedTime > 0) {
                try {
                    Thread.sleep(missedTime / 1000000, (int) (missedTime % 1000000));
                } catch (Exception ex) {
                 ex.printStackTrace();
                }
            }
            this.bytes -= CHUNK_LENGTH;
            this.lastTick = nowTick + (missedTime > 0 ? missedTime : 0);
        }
    }

}
